package com.hhf.feiojcodesandbox.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.hhf.feiojcodesandbox.enums.JudgeInfoMessageEnum;
import com.hhf.feiojcodesandbox.model.ExecuteCodeRequest;
import com.hhf.feiojcodesandbox.model.ExecuteCodeResponse;
import com.hhf.feiojcodesandbox.model.ExecuteMessage;
import com.hhf.feiojcodesandbox.model.JudgeInfo;
import com.hhf.feiojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author hhf
 * @Date 2024/10/31
 * @Description 模板方法设计模式
 */
@Slf4j
public abstract class CodeSandboxTemplate implements CodeSandbox {


    private static final String GLOBAL_CODE_DIR_NAME = "tempCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {

        log.info("代码沙箱开始执行...");
        List<String> inputList = executeCodeRequest.getInputList();
        String code = executeCodeRequest.getCode();

        //1. 把用户的代码保存为文件
        File userCodeFile = saveCodeToFile(code);

        //2. 编译文件 => .class
        try {
            compileFile(userCodeFile);
        } catch (IOException e) {
            e.printStackTrace();
            return getErrorResponse(e,JudgeInfoMessageEnum.COMPILE_ERROR.getValue());
        }

        //3. 执行.class文件,获取执行结果
        List<ExecuteMessage> executeMessageList = null;
        try {
            log.info("===================开始执行用户的代码========================");
            executeMessageList = getExecuteMessageList(inputList, userCodeFile.getParent());
        } catch (IOException e) {
            e.printStackTrace();
            return getErrorResponse(e,JudgeInfoMessageEnum.RUNTIME_ERROR.getValue());
        }

        //4. 封装结果,构造响应对象
        if (executeMessageList == null){
            getErrorResponse(new Throwable("系统异常"),JudgeInfoMessageEnum.SYSTEM_ERROR.getValue());
        }
        ExecuteCodeResponse executeCodeResponse = getExecuteCodeResponse(executeMessageList);


        //5. 文件清理
        clearFile(userCodeFile);

        //日志记录
        log.info("代码沙箱执行完毕...");

        return executeCodeResponse;
    }



    /**
     * 把用户的代码保存为文件
     *
     * @param code
     * @return
     */
    public File saveCodeToFile(String code) {

        String userDir = System.getProperty("user.dir");
        String golbalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        if (!FileUtil.exist(golbalCodePathName)) {
            FileUtil.mkdir(golbalCodePathName);
        }
        //将不同用户的提交代码进行隔离
        String userCodeParentPath = golbalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);

        return userCodeFile;
    }

    /**
     * 编译文件 => .class
     *
     * @param userCodeFile
     * @throws IOException
     */
    public void compileFile(File userCodeFile) throws IOException {

        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsoluteFile());

        Process compileProcess = Runtime.getRuntime().exec(compileCmd);
        ExecuteMessage compileExecuteMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
        log.info(compileExecuteMessage.toString());

    }

    /**
     * 执行.class文件,获取执行结果
     * @param inputList
     * @param userCodeParentPath
     * @return
     * @throws IOException
     */
    public List<ExecuteMessage> getExecuteMessageList(List<String> inputList, String userCodeParentPath) throws IOException {

        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);

            Process runProcess = Runtime.getRuntime().exec(runCmd);
            ExecuteMessage runExecuteMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
            log.info(runExecuteMessage.toString());
            executeMessageList.add(runExecuteMessage);

        }
        return executeMessageList;
    }

    /**
     * 封装结果,构造响应对象
     * @param executeMessageList
     * @return
     */
    public ExecuteCodeResponse getExecuteCodeResponse(List<ExecuteMessage> executeMessageList){
        //4. 封装结果,构造响应对象
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        // 输出用例 , 执行时间(取用时最大值，便于判断是否超时)
        long maxTime = 0;
        long maxMemory = 0;
        for (ExecuteMessage executeMessage : executeMessageList) {
            String errorMessage = executeMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                // 用户提交的代码执行中存在错误
                return getErrorResponse(new Throwable(errorMessage),JudgeInfoMessageEnum.RUNTIME_ERROR.getValue());
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
            Long memory = executeMessage.getMemory();
            if (memory != null) {
                maxMemory = Math.max(maxMemory, memory);
            }
        }
        // 正常运行完成
        if (outputList.size() == executeMessageList.size()) {
            // 用户提交的代码正常运行完成
            executeCodeResponse.setMessage("1");
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
        judgeInfo.setMemory(maxMemory);
        judgeInfo.setMessage(JudgeInfoMessageEnum.ACCEPTED.getValue());
        executeCodeResponse.setJudgeInfo(judgeInfo);

        return executeCodeResponse;
    }

    /**
     * 文件清理
     * @param userCodeFile
     */
    public void clearFile(File userCodeFile){
        //5.
        if (userCodeFile.getParent() != null){
            boolean del = FileUtil.del(userCodeFile.getParentFile().getPath());
            log.warn("删除" + (del ? "成功" : "失败"));
        }
    }


    /**
     * 获取错误处理
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e,String judgeInfoMessage) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());

        // 表示代码沙箱错误
        executeCodeResponse.setMessage("2");
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setMessage(judgeInfoMessage);
        judgeInfo.setMemory(-1L);
        judgeInfo.setTime(-1L);
        executeCodeResponse.setJudgeInfo(judgeInfo);

        return executeCodeResponse;
    }


}
